import datetime
import os

import xlrd as xlrd
from django.http import JsonResponse
from django.shortcuts import render
import time
from threading import Thread
from app.models import UploadExcelLog

from biquge import settings


def upload_excel(request):
    return render(request, 'index.html')


def get_upload_excel_log(request):
    logs = UploadExcelLog.objects.order_by('log_id')
    logs_list = []
    for log in logs:
        log_dict = {}
        log_dict['excel_path'] = log.excel_path
        log_dict['total_count'] = log.total_count
        log_dict['success_count'] = log.success_count
        log_dict['fail_count'] = log.fail_count
        log_dict['start_time'] = log.start_time
        log_dict['end_time'] = log.end_time
        logs_list.append(log_dict)
    return JsonResponse(logs_list, safe=False)


def upload_file(file, context):
    upload_excel_log = UploadExcelLog()

    t = int(time.time())
    file_name = '%d.xlsx' % t
    upload_excel_log.excel_path = file_name
    upload_excel_log.start_time = datetime.datetime.now()

    file_path = os.path.join(settings.MEDIA_ROOT[0], file_name)
    print(file_path)
    # 保存
    with open(file_path, 'wb+') as f:
        for chunk in file.chunks():
            f.write(chunk)

    # 读取excel
    wb = xlrd.open_workbook(file_path)
    sheet1 = wb.sheets()[0]
    nrows = sheet1.nrows
    context['total_rows'] = nrows

    upload_excel_log.total_count = nrows
    upload_excel_log.success_count = 0
    upload_excel_log.fail_count = 0
    upload_excel_log.save()

    print('总条数', nrows)


def do_upload(request):
    file = request.FILES.get('excel', '')
    content = {'total_rows': 0}
    th = Thread(target=upload_file, args=(file, content))
    th.start()
    return render(request, 'index.html', content)


def report(request):
    return render(request, 'report.html')


def json_data(request):
    data = {'product': ['1', '2', '3'],
            'Matcha Latte': ['Matcha Latte', 10, 20, 30]
            }
    return JsonResponse(data)
